package com.woniuxy.food.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.food.infra.mapper.FoodPicMapper;
import com.woniuxy.food.infra.mapper.FoodSkuMapper;
import com.woniuxy.food.infra.model.FoodPic;
import com.woniuxy.food.infra.model.FoodSku;
import com.woniuxy.food.infra.model.FoodSkuPic;
import com.woniuxy.food.infra.mapper.FoodSkuPicMapper;
import com.woniuxy.food.service.FoodSkuPicService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.food.service.servicedto.FoodSkuPicServiceDto;
import exception.MallException;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import result.CommonResultCodeEnum;

import java.util.List;

/**
 * <p>
 * 菜品图片表 服务实现类
 * </p>
 *
 * @author 刘德华
 * @since 2023-07-19
 */
@Service
public class FoodSkuPicServiceImpl extends ServiceImpl<FoodSkuPicMapper, FoodSkuPic> implements FoodSkuPicService {

    @Autowired
    private FoodSkuPicMapper foodSkuPicMapper;
    @Autowired
    private FoodSkuMapper foodSkuMapper;
    @Autowired
    private FoodPicMapper foodPicMapper;
    @Override
    @GlobalTransactional
    public void insertFoodSkuPic(Integer storeId,Integer skuId, Integer[] ids) {
        FoodSku foodSku = foodSkuMapper.selectById(skuId);
        if (foodSku==null) {
            throw new MallException("当前菜品sku不在", CommonResultCodeEnum.INVALID_PARAM);
        }
        for (Integer id : ids) {
            FoodSkuPic foodSkuPic = new FoodSkuPic();
            foodSkuPic.setSkuId(skuId);
            QueryWrapper<FoodPic> foodPicQueryWrapper = new QueryWrapper<>();
            foodPicQueryWrapper.eq("store_id",storeId).eq("food_pic_id",id);
            FoodPic foodPic = foodPicMapper.selectOne(foodPicQueryWrapper);
            if (foodPic==null) {
                throw new MallException("当前图片不存在",CommonResultCodeEnum.INVALID_PARAM);
            }
            foodSkuPic.setFilePath(foodPic.getPicPath());
            save(foodSkuPic);
        }
    }

    @Override
    public List<FoodSkuPicServiceDto> searchFoodSkuPic(Integer skuId) {
        FoodSku foodSku = foodSkuMapper.selectById(skuId);
        if (foodSku==null) {
            throw new MallException("当前菜品sku不在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<FoodSkuPic> foodSkuPicQueryWrapper = new QueryWrapper<>();
        foodSkuPicQueryWrapper.eq("sku_id",skuId);
        List<FoodSkuPic> foodSkuPics = foodSkuPicMapper.selectList(foodSkuPicQueryWrapper);
        List<FoodSkuPicServiceDto> foodSkuPicServiceDtos = BeanUtil.copyToList(foodSkuPics, FoodSkuPicServiceDto.class);
        return foodSkuPicServiceDtos;
    }
}
